﻿using DataSync.Entity;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Boco.CommonLib;
using System.IO;
using DataSync.Common;
using System.Xml.Linq;

namespace DataSync.Proc.Reader
{
    class LocalFileReader : FileDataReader
    {
        private static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        LocalFileConfig CurInputConf;  //本地目录文件配置
        private static object _lock = new object();

        protected override List<string> GetFileList()
        {
            //获取文件
            var files = Directory.GetFiles(CurInputConf.ReadDir, CurInputConf.FileMatch);
            return files.ToList();
        }

        protected override void ReadSourceConfig(XElement xmlnode)
        {
            //读取配置
            //var fconf = xmlnode.SelectSingleNode("LocalFileConfig");
            CurInputConf = new LocalFileConfig(base.CurReaderConf);
            CurInputConf.Type = "LocalFile";
            CurInputConf.FileMatch = xmlnode.GetAttribute("FileMatch");
            CurInputConf.ReadDir = xmlnode.GetAttribute("ReadDir");

            if (string.IsNullOrEmpty(CurInputConf.ReadDir))
            {
                throw new ApplicationException("ReadDir配置不正确");
            }
            //目录是否存在
            if (!Directory.Exists(CurInputConf.ReadDir))
            {
                throw new ApplicationException("ReadDir配置不正确");
            }
            if (string.IsNullOrEmpty(CurInputConf.FileMatch))
            {
                CurInputConf.FileMatch = "*";
            }
        }

        protected override void DeleteSourceFile(string file)
        {
            try
            {
                File.Delete(file);
            }
            catch (Exception ex)
            {
                log.Warn(string.Format("文件{0}删除失败", file), ex);
            }
        }
    }
}
